package com.aaa.mbs.controller;

import com.aaa.common.constants.ReturnStatus;
import com.aaa.common.util.Result;
import com.aaa.common.vo.MemberPassword;
import com.aaa.mbs.entity.Member;
import com.aaa.mbs.service.MemberService;
import com.aaa.mbs.util.ExcelUtil;
import com.aaa.mbs.util.PayUtil;
import com.aaa.mbs.util.SmsUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;


/**
 * (Member)表控制层
 *
 * @author makejava
 * @since 2020-12-04 15:21:10
 */
@RestController
@RequestMapping("member")
@SuppressWarnings("all")
public class MemberController {
    /**
     * 服务对象
     */
    @Resource
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;


    private Logger logger = LoggerFactory.getLogger(MemberController.class);

    /**
     * 修改密码
     * @return
     */
    @PostMapping("changePassword")
    public Result changePwd(@RequestBody  MemberPassword memberPassword){
         return memberService.changePassword(memberPassword);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ApiOperation("通过主键查询单条数据")
    public Member selectOne(Integer id) {
        return this.memberService.queryById(id);
    }

    /**
     * 根据用户名查询对象
     * @param userName
     * @return
     */
    @GetMapping("queryByUserName")
    public Member queryByUserName(@RequestParam("userName") String userName){
        return memberService.queryByUserName(userName);
    }

    /**
     * 根据电话或者用户名查询
     * @param userNameOrPhoneNum
     * @return
     */
    @GetMapping("queryMemberByParam")
    public Result queryMemberByParam(String phoneNum) {
        return memberService.queryMemberByParam(phoneNum);
    }

    /**
     * 查询所有分页加条件查询
     *
     * @param pageNo   第几页
     * @param pageSize 每页显示数量
     * @param member   实体
     * @return Result
     */
    @PostMapping("queryAll")
    @ApiOperation("查询所有分页加条件查询")
    public Result queryAll(@RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize, @RequestBody Member member) {
//        System.out.println(this.memberService.queryAllByParam(pageNo, pageSize, member));
        return this.memberService.queryAllByParam(pageNo, pageSize, member);
    }

    /**
     * 根据ID删除
     *
     * @param id id
     * @return Result
     */
    @DeleteMapping("deleteById")
    @ApiOperation("根据ID删除")
    public Result deleteById(Integer id) {
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), this.memberService.deleteById(id));
    }

    /**
     * 预支付
     * @param orderId
     * @param openid
     * @param request
     * @return
     */
    @GetMapping("/pay")
    public JSONObject pay(@RequestParam("orderId")String orderId,
                          @RequestParam(name = "openid") String openid, HttpServletRequest request){
        JSONObject jsonObject = PayUtil.wxPay(orderId,openid, request);
        return jsonObject;
    }

    /**
     * 手机端更新
     *
     * @param @param member 实例对象
     * @return Result
     */
    @PutMapping("updateFront")
    @ApiOperation("更新")
    public Result updateFront(@ApiParam("更新json数据") @RequestBody Member member) {
        System.out.println("id....."+member.getId());
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), this.memberService.updateFront(member));
    }
    /**
     * 更新
     *
     * @param @param member 实例对象
     * @return Result
     */
    @PutMapping("update")
    @ApiOperation("更新")
    public Result update(@ApiParam("更新json数据") @RequestBody Member member) {
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), this.memberService.update(member));
    }

    /**
     * 忘记密码
     * @param @param member 实例对象
     * @return Result
     */
    @PutMapping("forgetPwd")
    @ApiOperation("更新")
    public Result forgetPwd(@ApiParam("更新json数据") @RequestBody Member member) {
        Object verifyCode = redisTemplate.opsForValue().get(member.getPhoneNum());
//        System.out.println(member.getCode());
        //验证验证码
        if(verifyCode==null||!verifyCode.toString().equals(member.getCode())){
            return new Result(ReturnStatus.FAIL.getReturnCode(),
                    ReturnStatus.FAIL.getReturnMsg(), "验证码错误");
        }
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                    ReturnStatus.SUCCESS.getReturnMsg(),this.memberService.forgetPwd(member));
    }

    /**
     * 更新
     * @param @param member 实例对象
     * @return Result
     */
    @PutMapping("updatePwd")
    @ApiOperation("更新")
    public Result updatePwd(@ApiParam("更新json数据") @RequestBody Member member) {
        return this.memberService.updatePwd(member);
    }

    /**
     * 添加
     *
     * @param @param member 实例对象
     * @return Result
     */
    @PostMapping("insert")
    @ApiOperation("添加")
    public Result insert(@ApiParam("添加json数据") @RequestBody Member member) {
//        System.out.println(member.getCode());
        //logger.info(member.getCode());
        Object verifyCode = redisTemplate.opsForValue().get(member.getPhoneNum());
         //验证验证码
        if(verifyCode!=null||!verifyCode.toString().equals(member.getCode())){
            return new Result(ReturnStatus.FAIL.getReturnCode(),
                    ReturnStatus.FAIL.getReturnMsg(), "验证码错误");
        }
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), this.memberService.insert(member));
    }



    /**
     * 发送验证码
     * @param phoneNum
     * @return
     */
    @GetMapping("sentSM")
    public Result  sentSM(String phoneNum){
        return  new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), memberService.sendSM(phoneNum));
    }

    /**
     * 将member表导出到Excel表
     *
     * @return
     */

    @GetMapping("exportExcel")
    public String exportExcel(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd hhmmss");
        String sheetName = "用户信息";
        // 初始化数据
        List<Member> clientList = memberService.listMember();
        FileOutputStream out = null;
        //获取配置文件中保存对应excel文件的路径，本地也可以直接写成F：excel/testExcel
        String folderPath = ResourceBundle.getBundle("application").getString("downloadFolder") + File.separator + "testExcel";
        System.out.println(folderPath);
        //创建上传文件目录
        File folder = new File(folderPath);
        //如果文件夹不存在创建对应的文件夹
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //设置文件名
        String fileName = sdf1.format(new Date()) + sheetName + ".xls";
        // String savePath = folderPath + File.separator + fileName;
        response.setHeader("content-disposition",
                "attachment;fileName=" + fileName);
       /* try {


            out = new FileOutputStream(savePath);
            *//*out = new FileOutputStream(response.getOutputStream());*//*


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        ExcelUtil<Member> util = new ExcelUtil<Member>(Member.class); // 创建工具类.
        util.exportExcel(clientList, sheetName, 65536, response.getOutputStream()); // 导出
        System.out.println("----执行完毕----------");
        // System.out.println(savePath);
        //返回文件保存全路径
        return fileName;
    }

    /**
     * 导入Excel表
     * @param file
     * @return
     */
    @PostMapping("importExcel")
    public String importExcel(@RequestParam("file") MultipartFile file) {


        InputStream is = null;
        try {
            // @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件

            is = file.getInputStream();
            //下面是自己测试
            /*is = new FileInputStream("D:\\Poi测试\\会员测试.xls");*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelUtil excelUtil = new ExcelUtil(Member.class);
        List list = excelUtil.importExcel("用户信息", is);
        int n = 0;
        for (int i = 0; i < list.size(); i++) {
            Member member = (Member) list.get(i);
            System.out.println(member);
            n = memberService.insertBy(member);
            System.out.println("i值为：" + list.get(i));
        }
        if (n > 0) {
            return "success";
        }
        return "失败";
    }




}